<?php

use Drupal\shusy_cash\Entity\ShusyCash;
use Drupal\shusy_cash\ShusyCashHandleInterface;

function shusy_cash_shusy_cash_entity_form($form, &$form_state, ShusyCash $e, $op) {
  $form_state['build_info']['files']['form'] = drupal_get_path('module', 'shusy_cash') . '/shusy_cash.forms.inc';
  $form_state[ShusyCash::class] = $e;

  $form['amount'] = [
    '#type' => 'textfield',
    '#title' => t('提现金额'),
    '#default_value' => $e->amount / 100,
    '#disabled' => TRUE,
  ];

  if ($e->status == 0) {
    $form['handler'] = [
      '#type' => 'select',
      '#title' => t('提现方式'),
      '#required' => TRUE,
      '#options' => $e->getHandlerOptions(),
      '#default_value' => $e->handler,
      '#chosen' => TRUE,
    ];
  }

  field_attach_form($e->entityType(), $e, $form, $form_state);
  if ($e->status == 0) {
    $form['actions'] = ['#type' => 'actions'];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => t('通过'),
      '#submit' => ['shusy_cash_shusy_cash_entity_form_agree'],
    ];
    $form['actions']['delete'] = [
      '#type' => 'submit',
      '#value' => t('拒绝'),
      '#submit' => ['shusy_cash_shusy_cash_entity_form_deny'],
    ];
  }
  return $form;
}

function shusy_cash_shusy_cash_entity_form_agree($form, &$form_state) {
  $e = $form_state[ShusyCash::class];
  if ($e instanceof ShusyCash) {
    entity_form_submit_build_entity($e->entityType(), $e, $form, $form_state);
    $e->amount = bcmul($e->amount, 100);
    //通过
    $e->status = 1;
    $e->save();
    //处理中
    $e->status = 3;
    $e->save();
    $controller = shusy_cash_handler_init($e->handler);
    if ($controller instanceof ShusyCashHandleInterface) {
      $controller->handler($e);
    }
  }
}

function shusy_cash_shusy_cash_entity_form_deny($form, &$form_state) {
  $e = $form_state[ShusyCash::class];
  if ($e instanceof ShusyCash) {
    entity_form_submit_build_entity($e->entityType(), $e, $form, $form_state);
    $e->amount = bcmul($e->amount, 100);
    $e->status = 2;
    $e->save();
  }
}

function shusy_cash_shusy_cash_entity_form_submit($form, &$form_state) {
  $e = $form_state[ShusyCash::class];
  if ($e instanceof ShusyCash) {
    entity_form_submit_build_entity($e->entityType(), $e, $form, $form_state);
    $e->save();
  }
}

function shusy_cash_shusy_cash_delete_form($form, &$form_state, ShusyCash $e) {
  $form_state['build_info']['files']['form'] = drupal_get_path('module', 'shusy_cash') . '/shusy_cash.forms.inc';
  $form_state[ShusyCash::class] = $e;
  return confirm_form($form,
    t('Are you sure you want to delete %title?', ['%title' => $e->label()]),
    'admin/content/shusy_cash/' . $e->id,
    t('This action cannot be undone.'),
    t('Delete'),
    t('Cancel')
  );
}

function shusy_cash_shusy_cash_delete_form_submit($form, &$form_state) {
  $e = $form_state[ShusyCash::class];
  if ($e instanceof ShusyCash) {
    $e->delete();
  }
}

